package com.xuecheng.media.api;

import com.xuecheng.base.exception.XuChengException;
import com.xuecheng.base.model.RestResponse;
import com.xuecheng.media.model.dto.UploadFileParamsDto;
import com.xuecheng.media.service.MediaFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author luhao
 * @ClassName BigFilesController.java
 * @Description 大文件上传
 * @createTime 2023/7/6
 */
@RestController
@Slf4j
@Api(tags = "大文件上传接口")
public class BigFilesController {
    @Autowired
    private MediaFileService mediaFileService;

    @ApiOperation(value = "文件上传前检查文件")
    @PostMapping("/upload/checkfile")
    public RestResponse<Boolean> checkFile(@ApiParam(value = "上传文件md值") String fileMd5) {
        return mediaFileService.checkFiles(fileMd5);
    }

    @ApiOperation(value = "检查分块文件是否存在")
    @PostMapping("/upload/checkchunk")
    public RestResponse<Boolean> checkChunk(@ApiParam(value = "上传文件md值") String fileMd5,
                                            @ApiParam(value = "上传分块文件id值") Integer chunk) {
        return mediaFileService.checkChunk(fileMd5, chunk);
    }

    @ApiOperation(value = "上传分块文件")
    @PostMapping("/upload/uploadchunk")
    public RestResponse uploadChunk(@ApiParam(value = "file") MultipartFile file,
                                    @ApiParam(value = "fileMd5") String fileMd5,
                                    @ApiParam(value = "chunk") Integer chunk) {
        File tempFile = null;
        try {
            tempFile = File.createTempFile("minio", ".tmp");
            file.transferTo(tempFile);
        } catch (IOException e) {
            log.error("上传文件{},创建零时文件：{}失败", file.getOriginalFilename(), tempFile.getName());
            XuChengException.cast("创建零时文件失败");
        }
        String localPath = tempFile.getAbsolutePath();
        return mediaFileService.uploadChunk(localPath, fileMd5, chunk);
    }

    @ApiOperation(value = "合并分块文件")
    @PostMapping("/upload/mergechunks")
    public RestResponse mergeChunks(@ApiParam(value = "上传文件md5值") String fileMd5
            , @ApiParam(value = "上传分块文件名") String fileName
            , @ApiParam(value = "上传分块文件总数") Integer chunkTotal) {
        Long companyId = 1232141425L;
        UploadFileParamsDto uploadFileParamsDto = new UploadFileParamsDto();
        uploadFileParamsDto.setFilename(fileName);
        uploadFileParamsDto.setFileType("001002");
        uploadFileParamsDto.setTags("视频文件");
        return mediaFileService.mergeChunks(companyId,fileMd5, fileName, chunkTotal,uploadFileParamsDto);
    }
}
